package com.fqyd.campustransaction.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fqyd.campustransaction.model.Order;
import com.fqyd.campustransaction.model.OrderDetails;
import com.fqyd.campustransaction.model.User;
import com.fqyd.campustransaction.model.entity.OrderDetailsItem;
import com.fqyd.campustransaction.utils.Tools;

/**
 * 用户
 */
@Controller
@Scope(value = "prototype")
public class UserController extends BaseController {

	@RequestMapping("personal_info")
	public String personalInfo(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("loguser");
		user = userService.getById(user.getId());
		request.setAttribute("user", user);
		return "personal_info";
	}

	@RequestMapping("personal_order")
	public String personalOrder(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("loguser");
		user = userService.getById(user.getId());
		List<Order> orders = orderService.getByUserId(user.getId());
		List<OrderDetailsItem> orderDetailsItems = new ArrayList<>();
		for (int i = 0; i < orders.size(); i++) {
			List<OrderDetails> orderDetails = orderDetailsService.getByOrderId(orders.get(i).getId());
			OrderDetailsItem detailsGoods = new OrderDetailsItem();
			detailsGoods.setOrder(orders.get(i));
			detailsGoods.setOrderDetails(orderDetails);
			orderDetailsItems.add(detailsGoods);
		}
		request.setAttribute("orderDetailsItems", orderDetailsItems);
		return "personal_order";
	}

	@RequestMapping("personal_address")
	public String personalAddress(HttpServletRequest request) {
		String name = request.getParameter("name");
		String mobile = request.getParameter("mobile");
		String address = request.getParameter("address");
		User user = (User) request.getSession().getAttribute("loguser");
		user = userService.getById(user.getId());
		if (Tools.isNotEmpty(name) && Tools.isNotEmpty(mobile) && Tools.isNotEmpty(address)) {
			user.setName(name);
			user.setMobile(mobile);
			user.setAddress(address);
			userService.update(user);
		}
		request.setAttribute("user", user);
		return "personal_address";
	}
}
